package com.chuangsi.project.admin.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.chuangsi.project.admin.domain.UserProduct;
import com.chuangsi.project.admin.dto.admin.userproduct.ReqConfigureProductDto;
import com.chuangsi.project.admin.mapper.UserProductMapper;
import com.chuangsi.project.admin.service.UserProductService;
import com.chuangsi.project.system.domain.SysUser;
import com.chuangsi.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户产品中间表 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-09-02
 */
@Service
public class UserProductServiceImpl extends ServiceImpl<UserProductMapper, UserProduct> implements UserProductService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<String> getProductIdList(Long userId) {
        return list(Wrappers.lambdaQuery(UserProduct.class).select(UserProduct::getProductId).eq(UserProduct::getUserId,userId)).stream().map(UserProduct::getProductId).distinct().collect(Collectors.toList());
    }

    @Override
    public void configureProduct(ReqConfigureProductDto dto) {
        //先删除
        remove(Wrappers.lambdaUpdate(UserProduct.class).eq(UserProduct::getUserId,dto.getUserId()));
        //再新增
        if(dto.getProductIdList()!=null&&!dto.getProductIdList().isEmpty()){
            SysUser sysUser = sysUserService.getById(dto.getUserId());
            Assert.notNull(sysUser,"未找到账号");
            LocalDateTime now = LocalDateTime.now();
            for (String productId : dto.getProductIdList()) {
                UserProduct userProduct = new UserProduct();
                userProduct.setUserId(sysUser.getUserId());
                userProduct.setProductId(productId);
                userProduct.setCreateTime(now);
                userProduct.insert();
            }
        }
    }
}
